package com.zxh.blog.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import com.zxh.blog.MainActivity
import com.zxh.blog.R
import com.zxh.blog.bean.LoginResponse
import com.zxh.blog.bean.ResponseJson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException

class LoginActivity : AppCompatActivity() {

    // 返回按钮
    private lateinit var mBackBtn: ImageButton

    // 用户名输入框
    private lateinit var mUsernameEdit: EditText

    // 密码输入框
    private lateinit var mPasswordEdit: EditText

    // 登录按钮
    private lateinit var mLoginBtn: Button

    // 注册按钮
    private lateinit var mRegisterBtn: Button

    private val mJSON = "application/json".toMediaType()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        ImmersionBar.with(this)
            .statusBarColor(R.color.app_back)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .init()

        // 初始化控件
        mBackBtn = findViewById(R.id.btn_back)
        mUsernameEdit = findViewById(R.id.et_username)
        mPasswordEdit = findViewById(R.id.et_password)
        mLoginBtn = findViewById(R.id.btn_login)
        mRegisterBtn = findViewById(R.id.btn_register)

        // 注册按钮点击事件
        mRegisterBtn.setOnClickListener {
            // 跳转到注册页面
            startActivity(Intent(this, RegisterActivity::class.java))
        }
        // 返回按钮点击事件
        mBackBtn.setOnClickListener {
            // 销毁页面
            finish()
        }
        // 登录按钮点击事件
        mLoginBtn.setOnClickListener {
            // 获取输入的用户名和密码信息
            val username = mUsernameEdit.text.toString()
            val password = mPasswordEdit.text.toString()

            var loginFlag = true
            if (username.isEmpty()) {
                loginFlag = false
                Toast.makeText(this,"用户名不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (password.isEmpty()) {
                loginFlag = false
                Toast.makeText(this,"密码不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (loginFlag) {
                login(username, password, this)
            }
        }

    }

    /**
     *  登录
     */
    private fun login(username: String, password: String, context: Context) {
        val client = OkHttpClient()
        val url = "http://43.140.201.43:7777/login"
        val map = mutableMapOf<String, String>()
        map["username"] = username
        map["password"] = password
        val json = Gson().toJson(map)
        // 创建JSON格式的请求体
        val jsonRequestBody = json.toRequestBody(mJSON)

        // 创建POST请求
        val request = Request.Builder()
            .url(url)
            .post(jsonRequestBody)
            .build()

        // 发送请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败处理
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                // 获取响应结果
                val responseBody = response.body?.string()

                // 处理响应结果
                if (response.isSuccessful) {
                    // 请求成功，处理登录成功逻辑
                    // 可以通过responseBody解析服务器返回的数据
                    if (responseBody != null) {
                        val responseJson = parseJSONWithGSON(responseBody)
                        if (responseJson.code == 200) {
                            saveUserData(responseJson)
                            backMineFragment()
                            runOnUiThread {
                                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                } else {
                    // 请求失败，处理登录失败逻辑
                }
            }
        })
    }

    /**
     *  登录成功后，携带数据返回“我的”页面
     */
    private fun backMineFragment() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    /**
     *  保存用户信息
     */
    private fun saveUserData(response: ResponseJson<LoginResponse>) {
        val editor = getSharedPreferences("user_info", Context.MODE_PRIVATE).edit()

        // 保存token
        editor.putString("token", response.data?.token)

        // 保存userInfo
        editor.putString("avatar", response.data?.userInfo?.avatar)
        editor.putString("email", response.data?.userInfo?.email)
        editor.putString("id", response.data?.userInfo?.id)
        editor.putString("nickName", response.data?.userInfo?.nickName)
        var sex = response.data?.userInfo?.sex
        sex = if (sex == "1") {
            "男"
        } else {
            "女"
        }
        editor.putString("sex", sex)

        // 应用更改
        editor.apply()
    }

    /**
     *  解析JSON
     */
    private fun parseJSONWithGSON(jsonData: String): ResponseJson<LoginResponse> {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<LoginResponse>>() {}.type
        return gson.fromJson(jsonData, typeToken)
    }

}